import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, setFullToken, getFullToken, setSessionId, removeToken, removeSession } from '@/utils/auth'
import * as lock from '@/utils/lock'
import { action } from '@/micro/action'
const user = {
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      setToken(token)
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
      action.setGlobalState({ permission: state.permissions })
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      action.setGlobalState({ userInfo})
      const username = userInfo.username.trim()
      const password = userInfo.password
      const pinLogin = userInfo.pinLogin
      return new Promise((resolve, reject) => {
        login({username, password,pinLogin})
          .then((res) => {
            commit('SET_TOKEN', res)
            lock.unlock()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then((res) => {
            const { userInfo, tokenInfo } = res
            sessionStorage.setItem('userInfo', JSON.stringify({ userName: userInfo.username, userId: userInfo.userId, roleCode: userInfo.role.roleCode, roleName: userInfo.role.roleName }))
            const avatar =
              userInfo.avatar == '' || userInfo.avatar == null
                ? require('@/assets/images/profile.svg')
                : process.env.VUE_APP_BASE_API + userInfo.avatar
            if (userInfo.roleCodes && userInfo.roleCodes.length > 0) {
              // 验证返回的roles是否是一个非空数组
              commit('SET_ROLES', userInfo.roleCodes)
              commit('SET_PERMISSIONS', userInfo.permissionCodes)
            } else {
              commit('SET_ROLES', ['ROLE_DEFAULT'])
            }
            commit('SET_NAME', userInfo.username)
            setFullToken(tokenInfo)
            setSessionId(tokenInfo.sid)

            commit('SET_AVATAR', avatar)
            resolve(res)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.name)
          .then(() => {
            commit('SET_ROLES', [])
            commit('SET_PERMISSIONS', [])
            removeToken()
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        removeToken()
        removeSession()
        resolve()
      })
    },
  },
}

export default user
